package com.ceadeal.admin.util;

import com.ceadeal.admin.entity.User;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;

import java.security.Principal;

/**
 * 功能描述: OAuth2Util
 * @param
 * @return
 * @throws
 *
 * @author Yzw
 * @date 2017-03-24 13:11:24
 */
public class OAuth2Util {

    /**
     * 是否认证
     * @return
     */
    public static Boolean isAuthenticated(){
        return SecurityContextHolder.getContext().getAuthentication().isAuthenticated();
    }

    /**
     * 获取认证用户
     * @return
     */
    public static User getUser(){
        if (!isAuthenticated()) {
            return null;
        }
        Principal principal = SecurityContextHolder.getContext().getAuthentication();
        if(null == principal) {
            return null;
        }
        User user = JsonUtils.parseJSON(principal.getName(), User.class);
        return user;
    }

    /**
     * 获取token值
     * @return
     */
    public static String getTokenValue() {
        String tokenValue = null;
        Object details = SecurityContextHolder.getContext().getAuthentication().getDetails();

        if(null != details && details instanceof OAuth2AuthenticationDetails) {
            OAuth2AuthenticationDetails oDetails = (OAuth2AuthenticationDetails)details;

            tokenValue = oDetails.getTokenValue();
        }
        return tokenValue;
    }

    /**
     * 获取带token类型的请求头字符串（如：Bearer <tokenValue></tokenValue>）
     * @return
     */
    public static String getBearerTokenValue() {
        String tokenValue = null;
        Object details = SecurityContextHolder.getContext().getAuthentication().getDetails();

        if(null != details && details instanceof OAuth2AuthenticationDetails) {
            OAuth2AuthenticationDetails oDetails = (OAuth2AuthenticationDetails)details;

            tokenValue = oDetails.getTokenType() + " " + oDetails.getTokenValue();
        }
        return tokenValue;
    }
}
